# coding=utf-8

__author__ = 'Arthur Fortes'

from django import forms
from django.contrib.localflavor.br.forms import BRCPFField, BRCNPJField, BRPhoneNumberField, BRZipCodeField
from django.utils.safestring import mark_safe
from django.forms.widgets import CheckboxSelectMultiple, RadioSelect
from django.forms.util import ErrorList
from empresas.models import Empresa, Tipo_Empresa, Contatos

class HorizRadioRenderer(forms.RadioSelect.renderer):
    def render(self):
        return mark_safe(u'\n'.join([u'%s\n' % w for w in self]))


class EmpresaForm(forms.ModelForm):
    class Meta:
        model = Empresa

    TYPE_PERSON_CHOICE = (('0', 'Pessoa Jurídica'), ('1', 'Pessoa Física'))

    cnpj = BRCNPJField(label='CNPJ', required=False, widget=forms.TextInput(attrs={'alt': "cnpj"}))
    cep = BRZipCodeField(widget=forms.TextInput(attrs={'alt': 'cep'}))
    telefone = BRPhoneNumberField(widget=forms.TextInput(attrs={'alt': 'phone'}))
    tipo = forms.ModelMultipleChoiceField(label='Filiação', queryset=Tipo_Empresa.objects.all(),
        widget=CheckboxSelectMultiple(attrs={'class': 'validate[required]'}))
    cpf = BRCPFField(label='CPF', required=False, widget=forms.TextInput(attrs={'alt': "cpf"}))
    pessoa = forms.ChoiceField(widget=RadioSelect(renderer=HorizRadioRenderer, attrs={'class': 'validate[required]'}),
        choices=TYPE_PERSON_CHOICE, initial=0)
    comissao = forms.DecimalField(label='Comissão %', required=False,
        widget=forms.TextInput(attrs={'alt': "money-db"}))
    limitecompra = forms.DecimalField(label='Limite da Compra R$', required=False,
        widget=forms.TextInput(attrs={'alt': "money-db"}))
    tabelaprecovenda = forms.DecimalField(label='Acressimo na tabela de preço %', required=False,
        widget=forms.TextInput(attrs={'alt': "money-db"}))

    def clean(self):
        cnp = self.cleaned_data.get("cnpj")
        pes = self.cleaned_data.get("pessoa")
        cp = self.cleaned_data.get("cpf")
        msg = u"Este campo é obrigatório."

        if "0" in pes:
            if cnp == "":
                self._errors["cnpj"] = ErrorList([msg])
        if "1" in pes:
            if cp == "":
                self._errors["cpf"] = ErrorList([msg])

        return self.cleaned_data


class ContatoForm(forms.ModelForm):
    class Meta:
        model = Contatos

    telefoneresponsavel = BRPhoneNumberField(label='Telefone', widget=forms.TextInput(attrs={'alt': 'phone'}),
        required=False)
    aniversario = forms.DateField(widget=forms.TextInput(attrs={'alt': "date"}), required=False)